<template>
  <a-card class="general-card" title="优惠券" :bordered="false">
    <a-tabs @change="(val)=>{apiParams.promotionStatus = val}" :default-active-key="couponStatus">
      <a-tab-pane key="NEW" title="未开始"></a-tab-pane>
      <a-tab-pane key="START" title="已开始"></a-tab-pane>
      <a-tab-pane key="END" title="已结束"></a-tab-pane>
      <a-tab-pane key="CLOSE" title="已关闭"></a-tab-pane>
    </a-tabs>
    <searchTable
      :columns="columnsSearch"
      time-type="timestamp"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    ></searchTable>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="add"> 添加 </a-button>
          <a-button @click="delAll"> 批量关闭 </a-button>
          <a-button
            type="primary"
            status="danger"
            style="margin: 5px"
            @click="receivePage"
            >优惠券领取记录</a-button
          >
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getShopCouponList"
      :api-params="apiParams"
      :checkbox="true"
      :bordered="true"
      @selectTableChange="selectTableChange"
    >
      <template #price="{ data }">{{
        data.price
          ? unitPrice(data.price, '¥')
          : (data.couponDiscount || 0) + '折'
      }}</template>
      <template #num="{ data }">
        {{
          data.usedNum +
          '/' +
          data.receivedNum +
          '/' +
          (data.publishNum === 0 ? '不限制' : data.publishNum)
        }}
      </template>
      <template #time="{ data }">
        <div
          v-if="
            data?.getType === 'ACTIVITY' && data?.rangeDayType === 'DYNAMICTIME'
          "
          >长期有效</div
        >
        <div v-else-if="data.startTime && data.endTime"
          >{{ data.startTime }}<div style="margin: 0"></div
          >{{ data.endTime }}</div
        >
      </template>
      <template #edit="{ data }">
        <a-button
          v-if="
            data.promotionStatus == 'CLOSE' || data.promotionStatus == 'NEW'
          "
          style="margin-right: 10px"
          type="text"
          status="warning"
          @click="see(data)"
          >编辑</a-button
        >
        <a-button
          v-else
          style="margin-right: 10px"
          type="text"
          status="success"
          @click="see(data, 'onlyView')"
          >查看</a-button
        >
        <a-button
          v-if="
            data.promotionStatus == 'START' || data.promotionStatus == 'NEW'
          "
          style="margin-right: 10px"
          type="text"
          status="danger"
          @click="close(data)"
          >关闭</a-button
        >
        <a-button style="margin: 5px" type="text" @click="receivePage(data)"
          >领取记录</a-button
        >
      </template>
    </tablePage>
  </a-card>
</template>

<script setup lang="ts">
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import { getShopCouponList, updateCouponStatus } from '@/api/promotion';

  import {
    promotionsStatusRender,
    promotionsScopeTypeRender,
    couponType,
    promotionStatusSelect,
  } from '@/utils/tools';
  import { unitPrice } from '@/utils/filters';
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const tablePageRef = ref<any>();
  const couponStatus = ref<string>('START')
  const apiParams = ref<any>({ sort: 'startTime',promotionStatus:couponStatus.value });
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const selectList = ref([]); // 接受子组件传过来的值
  const columnsSearch: Array<SearchRule> = [
    {
      label: '优惠券名称',
      model: 'couponName',
      disabled: false,
      input: true,
    },
    {
      label: '活动时间',
      model: 'selectDate',
      disabled: false,
      datePicker: {
        type: 'range',
      },
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '活动名称',
      dataIndex: 'promotionName',
    },
    {
      title: '优惠券名称',
      dataIndex: 'couponName',
    },

    {
      title: '面额/折扣',
      dataIndex: 'price',
      slot: true,
      slotTemplate: 'price',
    },
    {
      title: '已使用/已领取/总数量',
      dataIndex: 'publishNum',
      slot: true,
      slotTemplate: 'num',
    },
    {
      title: '优惠券类型',
      dataIndex: 'couponType',
      slot: true,
      slotData: {
        badge: couponType,
      },
    },
    {
      title: '品类描述',
      dataIndex: 'scopeType',
      slot: true,
      slotData: {
        badge: promotionsScopeTypeRender,
      },
    },
    {
      title: '活动时间',
      width: 180,
      ellipsis: false,
      dataIndex: 'startTime',
      slot: true,
      slotTemplate: 'time',
    },
    {
      title: '状态',
      dataIndex: 'promotionStatus',
      slot: true,
      slotData: {
        badge: promotionsStatusRender,
      },
    },
  ];

  // todo 本页面操作列表为选择展示
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 280,
    methods: [
      {
        title: '编辑',
        slot: true,
        slotTemplate: 'edit',
      },
    ],
  };
  // 父组件传过来的数据
  const selectTableChange = (val: any) => {
    if (val) {
      selectList.value = val;
    }
  };
  // 查看/编辑
  const see = (v: any, only?: any) => {
    let data: any;
    only ? (data = { onlyView: true, id: v.id }) : (data = { id: v.id });
    router.push({
      name: 'add-coupon',
      query: data,
    });
  };
  // 批量关闭
  const delAll = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要下架的优惠券');
      return;
    }
    modal.confirm({
      title: '确认下架',
      content: `您确认要关闭所选的${selectList.value.length}条数据?`,
      alignCenter: false,
      onOk: async () => {
        const ids = [] as any;
        selectList.value.forEach((item: any) => {
          ids.push(item.id);
        });
        const params = {
          couponIds: ids.toString(),
          promotionStatus: 'CLOSE',
        };
        updateCouponStatus(params).then((res: any) => {
          if (res.data.success) {
            Message.success('优惠券关闭成功 ');
            tablePageRef.value.init();
          }
        });
      },
    });
  };
  // 关闭
  const close = (val: any) => {
    modal.confirm({
      title: '确认关闭',
      content: `确认要关闭此优惠券么?`,
      alignCenter: false,
      onOk: async () => {
        updateCouponStatus({
          couponIds: val.id,
          effectiveDays: 0,
        }).then((res: any) => {
          if (res.data.success) {
            Message.success('优惠券已关闭');
            tablePageRef.value.init();
          }
        });
      },
    });
  };
  // 添加优惠券
  const add = (val: any) => {
    router.push({
      name: 'add-coupon',
    });
  };
  // 优惠券领取记录
  const receivePage = (val?: any) => {
    val.id
      ? router.push({ name: 'coupon-receive', query: { id: val.id } })
      : router.push({ name: 'coupon-receive' });
  };
</script>
